package br.usp.icmc.biomac.client.view.impl;

import br.usp.icmc.biomac.client.view.DicomSearchWidget;
import br.usp.icmc.biomac.client.view.lixo.DicomResultModel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;



/**
 * @author amsnyder
 */

public class DicomSearchWidgetImpl extends Composite implements DicomSearchWidget {
    
	interface DicomSearchViewUiBinder extends UiBinder<Widget, DicomSearchWidgetImpl> {}
    
	private static DicomSearchViewUiBinder uiBinder = GWT.create(DicomSearchViewUiBinder.class);

	private Presenter presenter;

    @UiField ListBox searchTypeSelect;
	@UiField TextBox searchText;
 	@UiField Button searchButton;
 	@UiField Anchor myAccount;
 	@UiField Anchor logo;
 	@UiField Anchor home;
 	@UiField Anchor roi;
 	@UiField Anchor plugins; 
 	@UiField Anchor help; 	
 	@UiField Anchor signInOut;
 	


	public DicomSearchWidgetImpl() {
        initWidget(uiBinder.createAndBindUi(this));

        // put some id's and classes on the gwt widgets
        this.getWidget().getElement().setId("header");
        searchButton.getElement().setId("main-search-go");
        searchButton.getElement().addClassName("search-go");
        searchText.getElement().setId("main-search-box");
        searchText.getElement().addClassName("search-term");
        searchTypeSelect.getElement().setId("main-search-category");
        searchTypeSelect.getElement().setId("search-category");
        
        // fill out the select options
        searchTypeSelect.addItem("Patient Name", "patientName");
        searchTypeSelect.addItem("Patient ID", "patientId");
        searchTypeSelect.addItem("Accession #", "accessionNum");
        searchTypeSelect.addItem("Exam Type", "examType");
        searchTypeSelect.addItem("Study Date", "studyDate");
    }


    /**
     * Do a DicomSearch - on some cases it might take a while to return a result.
     * @param ClickEvent clickEvent
     */
	@UiHandler("searchButton")
	void handleSearchClickEvent(ClickEvent clickEvent){
        //updateSearchResultLabel();
        //presenter.setSearch(searchTypeSelect.getValue(), searchText.getValue() ); //for cell tree widget
        
        Integer categorySelected = searchTypeSelect.getSelectedIndex();
		String categoryValue = searchTypeSelect.getValue(categorySelected);
		//GWT.log("handleSearchClickEvent" + " =" + categoryValue + " =" + searchText.getValue());
        presenter.setSearch(categoryValue, searchText.getValue() ); 
    }
	
	 
	/**
	* Handle enter key for search 
    * @param KeyUpEvent event
	*/
	@UiHandler("searchText")
	public void onKeyUp(KeyUpEvent event)
    {
        if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER)
        {
            searchButton.click();
        }
     
    }

    /**
    * ROI nav bar item
    * @param clickEvent
    */
   @UiHandler("roi")
   void handleRoiClickEvent(ClickEvent clickEvent){
   }
   
   /**
    * Plugins nav bar item
    * @param clickEvent
    */
   @UiHandler("plugins")
   void handlePluginsClickEvent(ClickEvent clickEvent){
   }
   
   /**
    * Help nav bar item
    * @param clickEvent
    */
   @UiHandler("help")
   void handleHelpClickEvent(ClickEvent clickEvent){
	   new SettingsForm().center(); 
	   
   }
   
   /** 
    * Sign the user in and out.
    * @param clickEvent
    */
   @UiHandler("signInOut")
   void handleSignInOutClickEvent(ClickEvent clickEvent){
   	new LoginForm().center();
   }


    /**
     * Builds a new search result based on the search input text, and drop down.
     */
   /*
    private void updateSearchResultLabel(){
        int selectedIndex = searchTypeSelect.getSelectedIndex();
        NodeList<OptionElement> optionElements = searchTypeSelect.getOptions();
        String optionText = optionElements.getItem(selectedIndex).getText();

        String searchParam = searchText.getValue();
        searchResultSpan.setInnerText(optionText+": "+searchParam);
    }
    */

	@Override
	public Widget asWidget() {
		return this;
	}
	
    @SuppressWarnings("unused")
	private void sendSearchRequest(){
    	GWT.log("sendSearchRequest");

    //    String url = SearchUtil.getBaseURL()+"/search/?"+buildRequestData();
        String url = "http://127.0.0.1:8888/search/?"+buildRequestData();
        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
        SearchRequestCallback search = new SearchRequestCallback();
     
        requestBuilder.setCallback(search);//this.DicomResultGrid));
        try {
            requestBuilder.send();
        } catch (RequestException e) {
            //log.alert("RequestException: "+ e.getMessage());
        }
    }

    /**
     * Build the request data as sent to the DicomProxy.
     */
    private  String buildRequestData(){

        //String key = searchTypeSelect.getValue();
        Integer categorySelected = searchTypeSelect.getSelectedIndex();
		String key = searchTypeSelect.getValue(categorySelected);
        String value = searchText.getValue();
        return key+"="+value;
    }

    /**
     * Callback to handle search request.
     */
    class SearchRequestCallback implements RequestCallback {
    	DicomResultModel DicomResultModel;
   		@Override
        public void onResponseReceived(Request request, Response response) {
        	String responseText = response.getText();
            //parseStudyResponse the results and update the DicomTableWidget.
            if( 200 == response.getStatusCode()){
                

                if(!responseText.startsWith("Err")){
                    displayResult(responseText);
                }else{
                //    log.alert("----- Error -----\n"+responseText);
                }

            }else{
              //  log.alert("failed to get 200 response code");
            }

        }

        @Override
        public void onError(Request request, Throwable throwable) {

            //Clear the table and set search result.
            //log.alert("DicomProxy search error: "+throwable.getMessage());
        }

        /**
         * Put the results on the patients table.
         * @param responseText
         */
        private void displayResult(String responseText){
            DicomResultModel.parseStudyResponse(responseText);
        }

    }//class SearchRequestCallback

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

    
    // new code...
}
